package com.heroCW.bodhiAttic.controller;

import com.heroCW.bodhiAttic.resultUtil.Result;
import com.heroCW.bodhiAttic.resultUtil.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * 文件上传和下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload/**")
    public Result<String> upload(HttpServletRequest request, MultipartFile file) {
        log.info("file: {}", file.toString());

        // 获取url的最后路径
        String requestURI = request.getRequestURI();
        String router = Objects.requireNonNull(requestURI).substring(requestURI.lastIndexOf("/") + 1);


        String originalFilename = file.getOriginalFilename();
        String suffix = Objects.requireNonNull(originalFilename).substring(originalFilename.lastIndexOf("."));

        String fileName = UUID.randomUUID() + suffix;

        String newPath = basePath + router + "/";

        File dir = new File(newPath);

        if (!dir.exists()) {
            boolean flag = dir.mkdir();
            log.info("flag: {}", flag);
        }

        try {
            file.transferTo(new File(newPath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.success(ResultCode.UPLOAD_OK, fileName,"");
    }

    /**
     * 文件下载
     *
     * @param response
     * @param name
     */
    @GetMapping("/download/**")
    public void download(HttpServletRequest request, HttpServletResponse response, String name) {

        String requestURI = request.getRequestURI();
        // log.info("requestURI: {}", requestURI);
        String router = Objects.requireNonNull(requestURI).substring(requestURI.lastIndexOf("/") + 1);
        // log.info("router: {}", router);
        String newPath = basePath;
        if (!router.equals("download")) {
            newPath = newPath + router + "/";
        }
        // log.info("name: {}", name);

        try {
            // 通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(newPath + name);

            // 通过输出流将文件写回浏览器，在浏览器中展示图片
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int length;
            byte[] bytes = new byte[1024];
            while ((length = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
                outputStream.flush();
            }
            // 关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            log.error(e.toString());

        }


    }
}
